package cc.sends;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @ Description : SCAN Algorithm
 * @ Author : ChristosC
 * @ Date : 2020/12/16 21:39
 */
public class SCAN {
    List<Track> tracks;
    List<Track> upTracks;
    List<Track> downTracks;
    Track currTrack;

    float averageDistance;
    public void init(List<Track> tracks,Track currTrack){
        this.tracks = tracks;
        this.currTrack = currTrack;
        this.upTracks = new ArrayList<>();
        this.downTracks = new ArrayList<>();
        averageDistance = 0;
    }
    public void start(){
        Track pioneerTrack;
        int sumDistance = 0;
        DecimalFormat df = new DecimalFormat("#0.00");
        for(Track track : tracks){
            track.setDistanceToCurrTrack(currTrack.getTrackNum() - track.getTrackNum());
            if(track.getDistanceToCurrTrack()<0){
                track.setDistanceToCurrTrack(Math.abs(track.getDistanceToCurrTrack()));
                upTracks.add(track);
            }else {
                downTracks.add(track);
            }
        }
        while(downTracks.size()>0){

            if(upTracks.size()>0){
                // 取出 upTrack中 track.distanceToCurrTrack最小的
                pioneerTrack = getThePioneerTrack(upTracks);
                upTracks.remove(pioneerTrack);
            }else{
                // 取出 downTrack中 track.distanceToCurrTrack最小的
                pioneerTrack = getThePioneerTrack(downTracks);
                downTracks.remove(pioneerTrack);
            }
            pioneerTrack.setDistanceToCurrTrack(Math.abs(currTrack.getTrackNum() - pioneerTrack.getTrackNum()));
            sumDistance += pioneerTrack.getDistanceToCurrTrack();
            currTrack = pioneerTrack;
            System.out.println(pioneerTrack.getTrackNum()+ "\t" + pioneerTrack.getDistanceToCurrTrack());
        }
        averageDistance = (float)sumDistance/tracks.size();
        System.out.println("平均寻道长度："+df.format(averageDistance));
    }

    private Track getThePioneerTrack(List<Track> tracks){
        Track result = tracks.get(0);
        int min = tracks.get(0).getDistanceToCurrTrack();
        for(Track track : tracks){
            if(track.getDistanceToCurrTrack()<min){
                min = track.getDistanceToCurrTrack();
                result = track;
            }
        }
        return result;
    }

}
